package com.gotop.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gotop.api.service.ConfigService;
import com.gotop.common.enums.EnumStatus;
import com.gotop.common.enums.error.EnumClientError;
import com.gotop.common.exception.BaseException;
import com.gotop.common.utils.ClientGenerateUtil;
import com.gotop.common.utils.auth.CemUser;
import com.gotop.entity.system.Client;
import com.gotop.mapper.system.ClientDao;
import com.gotop.vo.config.ConfigParamVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @program: cem
 * @description:
 * @author: superfish
 * @create: 2021-01-04 15:17
 **/
@Service
public class ConfigServiceImpl implements ConfigService {

    @Autowired
    private ClientDao clientDao;

    @Override
    public boolean whether(ConfigParamVO configParamVO) {
        final Client client = clientDao.selectOne(
                new QueryWrapper<Client>()
                        .eq("tenantId", configParamVO.getTenantId())
                        .eq("type", 1)
                        .last("limit 1")
        );
        if (null != client) {
            return true;
        }
        return false;
    }

    @Override
    public boolean create(CemUser user, ConfigParamVO configParamVO) {
        final Client client = clientDao.selectOne(
                new QueryWrapper<Client>()
                        .eq("tenantId", configParamVO.getTenantId())
                        .eq("type", 1)
                        .last("limit 1")
        );

        if (null != client) {
            throw new BaseException(EnumClientError.ERROR_CODE7);
        }

        Client newClient = new Client();
        newClient.setName(configParamVO.getName());
        newClient.setClientId(ClientGenerateUtil.getUUID(16));
        newClient.setClientSecret(ClientGenerateUtil.getUUID(32));
        newClient.setCreateUser(user.getUserId());
        newClient.setType(1);
        newClient.setStatus(EnumStatus.FALSE.getCode());
        clientDao.insert(newClient);
        return true;
    }
}
